<?php

chdir(dirname(__FILE__)."/../..");
$path = getcwd();
chdir(dirname(__FILE__));

include_once $path."/../lib/core.class.php";


class EmailSnippet extends IPlugin 
{
    function EmailSnippet($parent = null)
    {
        IPlugin::IPlugin($parent);
        $this->tplfolder = dirname(__FILE__)."/tpl";
    }

    function getPluginTag() { return "email"; }
    function getPluginName() { return "Send email snippet"; }
    function getPluginVersion() { return "1.0.0"; }
    
    function doAction($params = null)
    {
//"to" => "jdoe@email.com",
//"from" => "me@myemail.com",
//"cc" => "me@myemail.com",
//"bcc" => "me@myemail.com",
//"subject" => "Test email",
//"body" => "Hiya test samples",
//"html" => "1",  // 1/0

        $headers = "";
        
        if( 1 == $params["html"])
        {
            // To send HTML mail, you can set the Content-type header.
            $headers .= "MIME-Version: 1.0\r\n"; 
            $headers .= "Content-type: text/html; charset=iso-8859-1\r\n"; 
        }
        
        // additional headers
        if("" != $params["from"])
        {
            $headers .= "From: {$params[from]}\r\n";
        }
        if("" != $params["cc"])
        {
            $headers .= "Cc: {$params[cc]}\r\n"; 
        }
        if("" != $params["bcc"])
        {
            $headers .= "BCc: {$params[bcc]}\r\n"; 
        }
    
//      debug(array($params, $headers), "EMAIL :::: DEBUG");
        #@mail($params["to"], $params["subject"], $params["body"], $headers);
    }
    
    
    
/*******************************************************************************************************************************/    
/************* Set confirmation code Begin *************************************************************************************/    
/*******************************************************************************************************************************/    

    function setConfirmationCode($arr_params)
    {
        /*
        $arr_params = array 
        (
            "id_item" => 1,// - id - order or ...
            "field_id_item" => "id",
            "table" => "orders",
            "field_confirmation" => "confirmation",
            "field_code_confirmation" => "code_confirmation",
            "field_with_date" => "pubdate",
            "min_length_code" => 10,
            "max_length_code" => 15,
            "email_to" => aa@aa.aa,
            "email_from" => bb@bb.bb,
            "name_user" => "Pupkin Vasya",
            "url" => "Pupkin Vasya", // url to click for confirmation
            "logo_name" => "Pupkin Vasya",
            "hours" => 24, // time live unconfirmation field
        );
        */

        $core = getCoreInstance();
        $db = $core->getProperty("db");

        if (1 != $db->getOne("select s_value from settings where s_key = 'purchase order'"))
        {
            return false;
        }

        $this->deleteUnconfirmationField($arr_params);

        // Generate code confirmation 
        $code_confirmation = $this->genStringBalderdash($arr_params['min_length_code'], $arr_params['max_length_code']);
         
        // Add in database code confirmation 
        $sql = "update {$arr_params[table]} set {$arr_params[field_confirmation]} = 'N'";
        $sql .= ", {$arr_params[field_code_confirmation]} = '" . str2db($code_confirmation) . "'";
        $sql .= " where {$arr_params[field_id_item]} = {$arr_params[id_item]}";
         
        $db->Exec($sql);
        
        // Get body e-mail
        $email_body = join("", file(dirname(__FILE__) . "/tpl/" . "email.tpl.php"));
        $email_body = str_replace("{name}", $arr_params['name_user'], $email_body);
        $email_body = str_replace("{logo_name}", $arr_params['logo_name'], $email_body);
        $email_body = str_replace("{url}", $arr_params['url'], $email_body);
        $email_body = str_replace("{code}", $code_confirmation, $email_body);
        $email_body = str_replace("{order}", $arr_params['id_item'], $email_body);
        debug($email_body);
        
        // Send e-mail
        $mail_params = array
        (
            "to" => $arr_params['email_to'],
            "from" => $arr_params['email_from'],
            "cc" => $arr_params['email_from'],
            "bcc" => $arr_params['email_from'],
            "subject" => "Confirmation",
            "body" => $email_body,
            "html" => "1",
        );
        $this->doAction($mail_params);
         
        return $code_confirmation;
    }

/*******************************************************************************************************************************/    
/************* Set confirmation code End ***************************************************************************************/    
/*******************************************************************************************************************************/    


/*******************************************************************************************************************************/    
/************* Compare confirmation code Begin *********************************************************************************/    
/*******************************************************************************************************************************/    

    function compareConfirmationCode($arr_params)
    {
        /*
        $arr_params = array 
        (
            "id_item" => 1,// - id - order or ...
            "field_id_item" => "id",
            "table" => "orders",
            "field_confirmation" => "confirmation",
            "field_code_confirmation" => "code_confirmation",
            "code" => "KJHJKhujhgjhgbJHGJHgjhgjhgh",
            "field_with_date" => "pubdate",
            "name_user" => "Pupkin Vasya",
            "hours" => 24, // time live unconfirmation field
        )
        */


        $core = getCoreInstance();
        $db = $core->getProperty("db");

        if (1 != $db->getOne("select s_value from settings where s_key = 'purchase order'"))
        {
            return false;
        }


        $this->deleteUnconfirmationField($arr_params);

        // Compare code confirmation 
        $sql = "select count(*) from {$arr_params[table]} where {$arr_params[field_id_item]} = {$arr_params[id_item]}";
        $sql .= " and {$arr_params[field_code_confirmation]} = '" . str2db($arr_params['code']) . "'";
        $compare_code_confirmation = $db->getOne($sql);
        
        if ($compare_code_confirmation > 0)
        {
            // Set in database confirmation
            $sql = "update {$arr_params[table]} set {$arr_params[field_confirmation]} = 'Y'";
            $sql .= " where {$arr_params[field_id_item]} = {$arr_params[id_item]}";
            $db->Exec($sql);
        }
        else
        {
            return false;
        }
        
        return true;
    }

/*******************************************************************************************************************************/    
/************* Compare confirmation code End ***********************************************************************************/    
/*******************************************************************************************************************************/    


/*******************************************************************************************************************************/    
/************* Delete Unconfirmation fields Begin ******************************************************************************/    
/*******************************************************************************************************************************/    

    function deleteUnconfirmationField($arr_params)
    {
        /*
        $arr_params = array
        (
            "hours" => 24, // time live unconfirmation field
            "table" => "orders",
            "field_confirmation" => "confirmation",
            "field_with_date" => "pubdate",
            "field_confirmation" => "confirmation",
        ) 
        */

        $core = getCoreInstance();
        $db = $core->getProperty("db");

        if (1 != $db->getOne("select s_value from settings where s_key = 'purchase order'"))
        {
            return false;
        }

        // Get now date 
        $now_time = time() - ($arr_params['hours'] * 60 * 60);
        $now_time = date("Y.m.d h:i:s", $now_time);

        $sql = "select count(*) from {$arr_params[table]} where {$arr_params[field_confirmation]} = 'N' and '{$now_time}' > {$arr_params[field_with_date]}";
        $num_fields = $db->getOne($sql);
        
        if ($num_fields > 0)
        {
            $sql = "delete from {$arr_params[table]} where {$arr_params[field_confirmation]} = 'N' and '{$now_time}' > {$arr_params[field_with_date]}";
            $db->Exec($sql);
        }
        
        return $num_fields;        
    }

/*******************************************************************************************************************************/    
/************* Delete Unconfirmation fields End ********************************************************************************/    
/*******************************************************************************************************************************/    



/*******************************************************************************************************************************/    
/************* Generate string with balderdash Begin ***************************************************************************/    
/*******************************************************************************************************************************/    

    function genStringBalderdash($min=8, $max=13)
    {
        $str = "";
        for($i = 0; $i < rand($min, $max); $i++)
        {
            $num = rand(48,122);
            if(($num > 97 && $num < 122))
            {
                $str .= chr($num);
            }
            elseif(($num > 65 && $num < 90))
            {
                $str.=chr($num);
            }
            elseif(($num >48 && $num < 57))
            {
                $str.=chr($num);
            }
            elseif($num == 95)
            {
                $str.=chr($num);
            }
            else
            {
                $i--;
            }
        }
        
        $str .= chr(rand(65, 90));
        $str .= chr(rand(48, 57));
        return $str;
    }

/*******************************************************************************************************************************/    
/************* Generate string with balderdash End *****************************************************************************/    
/*******************************************************************************************************************************/    
    
    
};

?>